package com.java.common.service;

import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.session.SessionRepository;
import org.springframework.session.web.http.SessionRepositoryFilter;
import org.springframework.stereotype.Component;

import com.java.common.constant.Constants;
import com.java.common.lang.domain.entity.User;
import com.java.common.utils.AssertKit;
import com.java.common.utils.ServletUtils;

/**
 * 前台token验证处理（PC端）
 *
 * @author yilabao
 * @date 2021年6月3日
 */
@Component
public class PcTokenService {

    private static final String PC_USER_SESSION_KEY = "PC_USER_SESSION_KEY";

    public boolean checkLogin(HttpServletRequest request) {
        User user = getLoginUser(request);
        boolean logged = user != null;
        if (logged) {
            request.setAttribute(Constants.LOGIN_USER_ATTRIBUTE, user);
            request.setAttribute(Constants.LOGIN_USER_UID_ATTRIBUTE, user.getUid());
        }
        return logged;
    }

    public void setLoginUser(User user) {
        AssertKit.notNull(user, "user不能为null");
        HttpSession session = ServletUtils.getSession();
        session.setAttribute(PC_USER_SESSION_KEY, user);
    }

    public User getLoginUser() {
        return getLoginUser(ServletUtils.getSession());
    }

    public User getLoginUser(HttpServletRequest request) {
        return getLoginUser(request.getSession());
    }

    public User getLoginUser(HttpSession session) {
        Object user = session.getAttribute(PC_USER_SESSION_KEY);
        if (user == null) {
            return null;
        }
        return (User) user;
    }

    public Long getLoginUserId() {
        return getLoginUser().getUid();
    }

    public boolean delLoginUser() {
        HttpSession session = ServletUtils.getSession();
        session.removeAttribute(PC_USER_SESSION_KEY);
        return getLoginUser() == null;
    }

    /**
     * 通过sessionId删除指定session
     * 
     * @author yilabao
     * @date 2022年1月18日
     * @param request
     * @param sessionId
     */
    public void removeSession(HttpServletRequest request, String sessionId) {
        HttpSession session = request.getSession();
        if (Objects.equals(sessionId, session.getId())) {
            session.invalidate();
            return;
        }
        Object sessionRepositoryAttribute = request.getAttribute(SessionRepositoryFilter.SESSION_REPOSITORY_ATTR);
        if (sessionRepositoryAttribute == null) {
            return;
        }
        SessionRepository<?> sessionRepository = (SessionRepository<?>) sessionRepositoryAttribute;
        if (sessionRepository.findById(sessionId) == null) {
            return;
        }
        sessionRepository.deleteById(sessionId);
    }

}